//
//  UIImageView+GCDImage.m
//  UI多线程
//
//  Created by 王建男 on 14-9-10.
//  Copyright (c) 2014年 WJN_work@163.com. All rights reserved.
//

#import "UIImageView+GCDImage.h"

@implementation UIImageView (GCDImage)

- (void)setImageWith:(NSString *)urlStr
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *path = [paths lastObject];
    
    NSString *file = [NSString stringWithFormat:@"%@/%d.data", @"Caches", [urlStr hash]];
    
    path = [NSString stringWithFormat:@"%@/%@", path, file];
    NSLog(@"%@", path);
    if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            @autoreleasepool {
                UIImage *image = nil;
                NSURL *url = [NSURL URLWithString:urlStr];
                NSData *data = [NSData dataWithContentsOfURL:url];
                [data writeToFile:path atomically:YES];
                image = [UIImage imageWithData:data];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self setImage:image];
                    [image release];
                });
            }
        });
    } else {
        UIImage *image = nil;
        NSData *data = [NSData dataWithContentsOfFile:path];
        image = [UIImage imageWithData:data];
        [self setImage:image];
        [image release];
    }
}

@end
